/**
 * wii核心功能，包括分享以及命名空间改造，PGV上报等能力
 * @author erikqin
 * @example
 * wii.conf = {share:{//分享内容},wx:{//wx签名}};
 */
(function() {
    var wxapi = "//res.wx.qq.com/open/js/jweixin-1.2.0.js",
        qqapi = "//open.mobile.qq.com/sdk/qqapi.js?_bid=152",
        qzapi = "//qzonestyle.gtimg.cn/qzone/phone/m/v4/widget/mobile/jsbridge.js?_bid=339",
        qnews = "//mat1.gtimg.com/auto/js/lib/newsJsBridge_160122.js";
    var load;

    function _load(url, onload) {
        var doc = document;
        var head = doc.head || (doc.getElementsByTagName("head")[0] || doc.documentElement);
        var node = doc.createElement("script");
        node.onload = onload;
        node.onerror = function() {};
        node.async = true;
        node.src = url[0];
        head.appendChild(node);
    }

    function _initWX(data) {
        if (!data.WXconfig) {
            return;
        }
        load([wxapi], function(wx) {
            if (!wx.config) {
                wx = window.wx;
            }
            var conf = data.WXconfig;
            wx.config({
                debug: conf.debug || false,
                appId: conf.appId,
                timestamp: conf.timestamp,
                nonceStr: conf.nonceStr,
                signature: conf.signature,
                jsApiList: conf.jsApiList
            });
            wx.error(function(res) {});
            wx.ready(function() {
                var config = {
                    title: data.title,
                    desc: data.summary,
                    link: data.url,
                    imgUrl: data.pic,
                    type: "",
                    dataUrl: "",
                    success: function() {
                        data.callback && data.callback();
                    },
                    cancel: function() {}
                };
                //将微信函数注册到wii命名空间
                registerFunction(data.funcNames);
                wx.onMenuShareAppMessage(config);
                wx.onMenuShareQQ(config);
                wx.onMenuShareQZone(config);
                if (conf.swapTitleInWX) {
                    wx.onMenuShareTimeline({
                        title: data.summary,
                        desc: data.title,
                        link: data.url,
                        imgUrl: data.pic,
                        type: "",
                        dataUrl: "",
                        success: function() {
                            data.callback && data.callback();
                        },
                        cancel: function() {}
                    });
                } else {
                    wx.onMenuShareTimeline(config);
                }
            });
        });
    }

    function _initQQ(data) {
        var info = {
            title: data.title,
            desc: data.summary,
            share_url: data.url,
            image_url: data.pic
        };

        function doQQShare() {
            try {
                if (data.callback) {
                    window.mqq.ui.setOnShareHandler(function(type) {
                        if (type == 3 && (data.swapTitle || data.WXconfig && data.WXconfig.swapTitleInWX)) {
                            info.title = data.summary;
                        } else {
                            info.title = data.title;
                        }
                        info.share_type = type;
                        info.back = true;
                        window.mqq.ui.shareMessage(info, function(result) {
                            if (result.retCode === 0) {
                                data.callback && data.callback.call(this, result);
                            }
                        });
                    });
                } else {
                    window.mqq.data.setShareInfo(info);
                }
            } catch (e) {}
        }
        if (window.mqq) {
            doQQShare();
        } else {
            load([qqapi], function() {
                doQQShare();
            });
        }
    }

    function _initQZ(data) {
        function doQZShare() {
            if (QZAppExternal && QZAppExternal.setShare) {
                var imageArr = [],
                    titleArr = [],
                    summaryArr = [],
                    shareURLArr = [];
                for (var i = 0; i < 5; i++) {
                    imageArr.push(data.pic);
                    shareURLArr.push(data.url);
                    if (i === 4 && (data.swapTitle || data.WXconfig && data.WXconfig.swapTitleInWX)) {
                        titleArr.push(data.summary);
                        summaryArr.push(data.title);
                    } else {
                        titleArr.push(data.title);
                        summaryArr.push(data.summary);
                    }
                }
                QZAppExternal.setShare(function(data) {}, {
                    "type": "share",
                    "image": imageArr,
                    "title": titleArr,
                    "summary": summaryArr,
                    "shareURL": shareURLArr
                });
            }
        }
        if (window.QZAppExternal) {
            doQZShare();
        } else {
            load([qzapi], function() {
                doQZShare();
            });
        }
    }

    function _initQNews() {
        var info = {
            title: data.title,
            desc: data.summary,
            linkUrl: data.url,
            imgUrl: data.pic
        };

        function getShareInfo() {
            return JSON.stringify({
                "can_share": "1"
            });
        }

        function getNewsShareInfo() {
            var news_shareinfo = JSON.stringify(info);
            return news_shareinfo;
        }

        window.getShareInfo = getShareInfo;
        window.getNewsShareInfo = getNewsShareInfo;

        load([qnews], function() {
            console.log('新闻客户端js加载完成！');
        });
    }

    function init(opts) {
        var ua = navigator.userAgent;
        var isWX = ua.match(/MicroMessenger\/([\d\.]+)/),
            isQQ = ua.match(/QQ\/([\d\.]+)/),
            isQZ = ua.indexOf("Qzone/") !== -1,
            isNews = ua.match("/qqnews/i");
        isWX && _initWX(opts);
        isQQ && _initQQ(opts);
        isQZ && _initQZ(opts);
        isNews && _initQNews(opts);
    }

    function registerFunction(funcNames){
        for(var i in funcNames){
            var funcName = funcNames[i]; 
            wii['wx'][funcName] = function(){
                wx[funcName][apply](this, arguments);
            }
        }
    }

    load = _load;

    if (wii && wii.wx && wii.wx.config) {
        var share = wii.share;
        var config = wii.wx.config;
        init({
            title: share.title, // 分享标题
            summary: share.summary, // 分享内容
            pic: share.pic, // 分享图片
            url: share.url, // 分享链接，需要做处理，避免当前地址带参数
            // 微信权限验证配置信息，若不在微信传播，可忽略
            WXconfig: {
                swapTitleInWX: config.debug || false, // 是否标题内容互换（仅朋友圈，因朋友圈内只显示标题）
                appId: config.appId, // 公众号的唯一标识
                timestamp: config.timestamp, // 生成签名的时间戳
                nonceStr: config.nonceStr, // 生成签名的随机串
                signature: config.signature, // 签名
                jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone"]
            },
            funcNames: ['addCard','scanQRCode']
        });
    }

    if (wii && wii.pgv) {
        load(['//pingjs.qq.com/ping.js'], function() {
            if (typeof(pgvMain) == 'function') {
                pgvMain();
            }
        });
    }
})();
